package demo01;


import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Test {
    public static void main(String[] args) {

    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (root == null) {
            return list;
        } else {
            TreeNode head = root;
            stack.push(head);
            while (!stack.isEmpty()) {
                //cur遍历二叉树
                //head 表示上一个结点
                TreeNode cur = stack.peek();
                //有左树且左树没处理
                if (cur.left != null && cur.left != head && cur.right != head) {
                    stack.push(cur.left);
                    continue;
                } else if (cur.right != null && cur.right != head) {
                    //有右树且未处理
                    stack.push(cur.right);
                } else {
                    list.add(stack.peek().val);
                    head = stack.pop();
                }
            }
        }
        return list;
    }
}
/*
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (root == null) {
            return list;
        } else {
            stack.push(root);
            TreeNode cur = root;
            while (!stack.isEmpty()) {
                if ((root.left==null&&root.right==null)||(root.left==cur||root.right==cur)) {
                    list.add(cur.val);
                    cur = stack.pop();
                    continue;
                }
                if(root.left!=null) {
                    stack.push(root.left);
                    root = root.left;
                    continue;
                }
                if(root.right!=null) {
                    stack.push(root.right);
                    root = root.right;
                }
            }
        }
        return list;
    }
}*/
